package com.haibei.activity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewParent;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.common.uitl.LogUtil;
import com.common.uitl.SharePersistent;
import com.common.uitl.Tool;
import com.haibei.App;
import com.haibei.R;
import com.haibei.view.MainViewFactory;
import com.haibei.view.SingleTabInidcatorView;
import com.haibei.view.SubTabView;
import com.haibei.view.SubTabViewArticle;
import com.haibei.view.SubTabViewArticle.OnSlideButtonClickListener;
import com.haibei.view.Tab;
import com.haibei.view.Tab.OnTabClickListener;
import com.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.slidingmenu.lib.SlidingMenu.OnOpenedListener;

public class MainActivity extends BaseSlideActivity {

	private RelativeLayout mRelativeLayoutContainer;
	private LinearLayout mLinearLayoutTab;
	private Tab mTab;
	private SubTabView currentSubTab;
	private SubTabViewArticle subTabViewArticle;
	private RelativeLayout relativeLayoutMain;
	private final String STRING_LOCATION_PERMIT = "location_key";
	public static boolean isLocationPermit;
	private LocationClient mLocClient;
	private int INT_GO_LOGIN = 500;
	public static boolean isForeground = false;
	private String tempSlecctId = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		slidingMenu.setOnClosedListener(new OnClosedListener() {
			@Override
			public void onClosed() {
				if (currentSubTab instanceof SubTabViewArticle) {
					// LogUtil.i(App.tag, "menuClosed:检测类别更新....");
					if (!tempSlecctId.equals(SubTabViewArticle.categoryId)) {// 如果id发生变化
						SubTabViewArticle sb = ((SubTabViewArticle) currentSubTab);
						sb.hideEmpty();//先隐藏 搜索结果为空的
						sb.requestFirst();
					}
				}
			}
		});
		slidingMenu.setOnOpenedListener(new OnOpenedListener() {
			@Override
			public void onOpened() {
				tempSlecctId = SubTabViewArticle.categoryId;
			}
		});
	
	}

	public void initView() {
		setContentView(R.layout.activity_main);
		mLocClient = App.getApp().mLocationClient;
		relativeLayoutMain = findRelativeLayout(R.id.relativeLayoutMain);
		mRelativeLayoutContainer = findRelativeLayout(R.id.relativeLayoutContent);
		mLinearLayoutTab = findLinearLayout(R.id.linearLayoutTab);
		mTab = new Tab(this);
		mTab.clearTabs();
		subTabViewArticle = MainViewFactory.getConsultView(this);
		subTabViewArticle.setOnSlideButtonClickListener(new OnSlideButtonClickListener() {
			@Override
			public void OnSlideClick() {
				if (!slidingMenu.isMenuShowing()) {
					slidingMenu.showMenu();
					// cosultView.getHeaderView().setBackgroundResource(R.drawable.bg_top_bar_rect);
				} else {
					slidingMenu.showContent(true);
					// cosultView.getHeaderView().setBackgroundResource(R.drawable.bg_top_bar);
				}

			}
		});

		mTab.addTab(new SingleTabInidcatorView(this, R.drawable.icon_consult, R.drawable.icon_consult_p, "资讯", subTabViewArticle));
		mTab.addTab(new SingleTabInidcatorView(this, R.drawable.icon_topic, R.drawable.icon_topic_p, "话题", MainViewFactory
				.getTopicView(this)));
		mTab.addTab(new SingleTabInidcatorView(this, R.drawable.icon_shoping, R.drawable.icon_shoping_p, "海淘", MainViewFactory
				.getMarket(this)));
		mTab.addTab(new SingleTabInidcatorView(this, R.drawable.icon_infocenter, R.drawable.icon_infocenter_p, "个人中心", MainViewFactory
				.getUserCenterView(this)));
		mTab.setOnTabClickListener(new OnTabClickListener() {
			@Override
			public void onClick(SingleTabInidcatorView indicator) {// 点击某个tabIndicator，展示对应的indicatorView
				currentSubTab = indicator.getSubTab();
				mRelativeLayoutContainer.removeAllViews();// 这里的removeAllViews为什么不能全部删除，难道是并发的原因
				View tabView = indicator.getTabContentView();// 这里竟然可能出现异常说：tabView已经被添加了，不能再添加，而事实上已经调用父布局的removeAllViews
				ViewParent vg = tabView.getParent();
				if (null != vg) {
					RelativeLayout rp = (RelativeLayout) vg;
					rp.removeAllViews();// 必须在这里强制调用一次删除父布局的视图，why，不是已经删除过么，不理解
				}
				mRelativeLayoutContainer.addView(tabView);
				indicator.getSubTab().onShow();
				// if(currentSubTab instanceof SubTabViewUserCenter){
				// if(!App.isLogin()){
				// Intent i = new Intent();
				// i.setClass(MainActivity.this, LoginActivity.class);
				// startActivityForResult(i, INT_GO_LOGIN);
				// }
				// }
			}
		});
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		mLinearLayoutTab.addView(mTab.getView(), lp);

		mTab.check(0);

		// /============
		isLocationPermit = SharePersistent.getBoolean(MainActivity.this, STRING_LOCATION_PERMIT);
		if (isLocationPermit) {
			startLocation();
		} else {
			showPermitLocationDialog();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		isForeground=true;
	}
	@Override
	protected void onPause() {
		super.onPause();
		isForeground=false;
	}
	
	public void showMenu() {
		slidingMenu.showMenu();
	}

	public void showContent() {
		slidingMenu.showContent(true);
	}

	/** 开始廷尉 */
	private void startLocation() {
		setLocationOption();
		mLocClient.start();
		mLocClient.requestLocation();
		LogUtil.i(App.tag, "开始定位.......");
	}

	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true); // 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setServiceName("com.baidu.location.service_v2.9");
		option.setAddrType("all");// 所有地址
		option.setScanSpan(500);// 设置定位模式，小于1秒则一次定位;大于等于1秒则定时定位
		option.setPriority(LocationClientOption.NetWorkFirst); // 设置网络优先
		option.disableCache(true);
		mLocClient.setLocOption(option);
	}

	@Override
	protected void onDestroy() {
		mLocClient.stop();
		super.onDestroy();
	}

	/**
	 * 是否允许定位
	 */
	private void showPermitLocationDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("是否允许定位？");
		builder.setTitle("提示");
		builder.setPositiveButton("允许", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				SharePersistent.saveBoolean(MainActivity.this, STRING_LOCATION_PERMIT, true);
				startLocation();
			}
		});

		builder.setNegativeButton("拒绝", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				SharePersistent.saveBoolean(MainActivity.this, STRING_LOCATION_PERMIT, false);
			}
		});
		builder.create().show();
	}

	private long mExitTime;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (slidingMenu.isMenuShowing()) {
			return super.onKeyDown(keyCode, event);
		}

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if ((System.currentTimeMillis() - mExitTime) > 2000) {
				Tool.ToastShow(MainActivity.this, "再按一次退出！");
				mExitTime = System.currentTimeMillis();
			} else {
				Intent i = new Intent();
				i.setClass(MainActivity.this, WelcomActivity.class);
				i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				i.putExtra("flag", -1);
				startActivity(i);
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (null != currentSubTab) {
			currentSubTab.onActivityResult(requestCode, resultCode, data);
		}
	}
}
